var app = angular.module('wetterLuchs', []);

// Controller with several API calls (dependent on e.a.) ("Promises-Chaining")
// http://bit.ly/1PijnPx
app.controller('WeatherCtrl', ['$scope', '$http', 'timeAgo', function($scope, $http, timeAgo) {
        geoLat =30.6667;
        geoLong =104.0667;
        $scope.geoCoordinates = geoLat + ',' + geoLong;
        var lang = 'zh';
        urls = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + $scope.geoCoordinates + '&result_type=locality&key=AIzaSyCg3yL1Xhg-f9twY7PS7kDLzM-0SKBwHCY';
        var getCityObj = {
               "results" : [
                  {
                     "address_components" : [
                        {
                           "long_name" : "成都市",
                           "short_name" : "成都市",
                           "types" : [ "locality", "political" ]
                        },
                        {
                           "long_name" : "四川省",
                           "short_name" : "四川省",
                           "types" : [ "administrative_area_level_1", "political" ]
                        },
                        {
                           "long_name" : "中国",
                           "short_name" : "CN",
                           "types" : [ "country", "political" ]
                        }
                     ],
                     "formatted_address" : "中国四川省成都市",
                     "geometry" : {
                        "bounds" : {
                           "northeast" : {
                              "lat" : 31.4353345,
                              "lng" : 104.8927951
                           },
                           "southwest" : {
                              "lat" : 30.09429739999999,
                              "lng" : 102.9928858
                           }
                        },
                        "location" : {
                           "lat" : 30.572815,
                           "lng" : 104.066801
                        },
                        "location_type" : "APPROXIMATE",
                        "viewport" : {
                           "northeast" : {
                              "lat" : 30.8581695,
                              "lng" : 104.3261719
                           },
                           "southwest" : {
                              "lat" : 30.4588876,
                              "lng" : 103.8249207
                           }
                        }
                     },
                     "place_id" : "ChIJIXdEACPF7zYRAg4kLs5Shrk",
                     "types" : [ "locality", "political" ]
                  }
               ],
               "status" : "OK"
            };

        console.log(getCityObj);
        $scope.getCityName = getCityObj.results[0].address_components[0].short_name;
        return $http({
            method: 'JSONP',
            url: 'https://api.darksky.net/forecast/1d96cc3ef09464128ca17edb27b686c6/' + $scope.geoCoordinates + '?units=si&lang='+lang+'&callback=JSON_CALLBACK'
        })
        .then(function(response) {
                $scope.currentWeather = response.data;

                var currentWeatherIcon = response.data.currently.icon;

                var unsplashImgQuery = '';

                switch (currentWeatherIcon) {
                    case 'clear-day':
                        unsplashImgQuery = 'sun';
                        break;
                    case 'clear-night':
                        unsplashImgQuery = 'night';
                        break;
                    case 'cloudy':
                        unsplashImgQuery = 'cloudy';
                        break;
                    case 'fog':
                        unsplashImgQuery = 'fog';
                        break;
                    case 'partly-cloudy-day':
                        unsplashImgQuery = 'clouds';
                        // not ideal search term
                        break;
                    case 'partly-cloudy-night':
                        unsplashImgQuery = 'night';
                        // not ideal search term
                        break;
                    case 'rain':
                        unsplashImgQuery = 'rain';
                        break;
                    case 'sleet':
                        unsplashImgQuery = 'snow';
                        // not ideal search term
                        break;
                    case 'snow':
                        unsplashImgQuery = 'snow';
                        break;
                    case 'wind':
                        unsplashImgQuery = 'wind';
                        break;
                    default:
                        console.log('Forecast Icon Error!');
                }

                // Add to Image Query: Background Image with optimum size for device orientation
                // Implemented via viewport dimension comparison (easier than device-orientation + desktop browser compatible)

                var viewportWidth = window.innerWidth;
                var viewportHeight = window.innerHeight;
                var bgImageOrientation;

                if (viewportHeight > viewportWidth){
                    // Portrait orientation / viewport
                    bgImageOrientation = '&h=1000';
                } else {
                    // Landscape orientation / viewport
                    bgImageOrientation = '&w=1000';
                }


                return $http({
                    method: 'GET',
                    url: 'https://api.unsplash.com/photos/random?query=' + unsplashImgQuery + '&client_id=5a84b2ae1a2e983ee9e8850ac318152957f24614e0acb83896f7ba381ed6601f' + bgImageOrientation
                })
        })
        .then(function(response) {

        //console.log('Unsplash Img Query: ', response.data);
        //console.log('Unsplash Img Large: ', response.data.urls.regular);
        //console.log('Photo taken by: ', response.data.user.name);
        //console.log('Photographer URL: ', response.data.user.links.html);
        //console.log('Photo main color: ', response.data.color);

        $scope.unsplashPhoto = response.data;

        var unsplashRandImgUrl = response.data.urls.custom;
        // urls.custom = query param (see above), urls.regular = 1080 w

        $scope.bgImgCurrentWeather = {
            'background-image': 'url(' + unsplashRandImgUrl + ')'
        };

        return $http({
            method: 'JSONP',
            url: 'https://api.darksky.net/forecast/1d96cc3ef09464128ca17edb27b686c6/' + $scope.geoCoordinates + ',' + timeAgo.timeAgoFunc(7) + '?units=si&'+lang+'&callback=JSON_CALLBACK'
        })

    })

    .then(function (response) {
        $scope.weather1week = response.data;

        return $http({
            method: 'JSONP',
            url: 'https://api.darksky.net/forecast/1d96cc3ef09464128ca17edb27b686c6/' + $scope.geoCoordinates + ',' + timeAgo.timeAgoFunc(10 * 365 + 2) + '?units=si&'+lang+'&callback=JSON_CALLBACK'
        })
    })

    .then(function (response) {
        $scope.weather10years = response.data;

        return $http({
            method: 'JSONP',
            url: 'https://api.darksky.net/forecast/1d96cc3ef09464128ca17edb27b686c6/' + $scope.geoCoordinates + ',' + timeAgo.timeAgoFunc(25 * 365 + 6) + '?units=si&'+lang+'&callback=JSON_CALLBACK'
        })
    })

    .then(function (response) {
        $scope.weather25years = response.data;
    })

}]);


app.factory('timeAgo', function() {
    return {
        timeAgoFunc: function(timeDiffDays) {
            var currentDateString = new Date();
            currentDateString.setTime(currentDateString.valueOf() - (timeDiffDays * 24 * 60 * 60 * 1000));
            // "valueOf" gets number out of (date-)string
            // JS Date needs ms (below converted back to sec for API)
            // TODO: dynamically count in leap-years
            var endDateSec = currentDateString.valueOf() / 1000;
            var endDateStripped = endDateSec | 0;
            // "Bitwise Operator" --> stripping digits after decimal point
            return endDateStripped;
        }
    }
});

app.filter('tempCelsius', function() {
    return function(input) {
        var output;
        if (input == '') {
            output = '';
        } else {
            output = input + '\xB0C';
        }
        return output;
    }
});

app.directive('myDataLoader', function() {
   return {
       restrict: 'E',
       scope: {
           hideIf: '=data' // Connection to template (below) --> makes directive dynamic
       },
       template: '<span class="data-label" ng-hide="hideIf"><em><small>(lade Daten...)</small></em></span>'
   };
});
